package com.ziyucoding.springboot.labs.lab4.concurrentdemo.example.aqs;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;

/**
 * CyclicBarrier 示例1
 * CyclicBarrier：计数器可以被重置，多个线程相互等待。
 *
 * @author ziyucoding
 * @date 2022-10-27
 **/
@Slf4j
public class CyclicBarrierExample1 {

    private static CyclicBarrier barrier = new CyclicBarrier(3);

    public static void main(String[] args) throws InterruptedException {
        ExecutorService executorService = Executors.newCachedThreadPool();
        for (int i = 0; i < 10; i++) {
            final int num = i;
            Thread.sleep(1000);
            executorService.execute(() -> {
                try {
                    test(num);
                } catch (Exception e) {
                    log.error("发生异常", e);
                }
            });
        }

        log.info("finish");
        executorService.shutdown();
    }

    /**
     * 测试
     *
     * @param num
     * @return void
     **/
    private static void test(int num) throws InterruptedException, BrokenBarrierException {
        Thread.sleep(1000);
        log.info("{} is ready", num);
        barrier.await();
        log.info("{} continue", num);
    }
}
